package cn.texous.starter.sms.config;

import cn.texous.starter.sms.config.properties.AliyunSmsProperties;
import cn.texous.starter.sms.config.properties.SmsProperties;
import cn.texous.starter.sms.handler.AliyunSmsHandler;
import cn.texous.starter.sms.handler.SmsHandler;
import cn.texous.starter.sms.handler.TencentSmsHandler;
import cn.texous.starter.sms.handler.YunZhiXunSmsHandler;
import cn.texous.starter.sms.service.SmsService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/8/23 9:33
 */
@Configuration
@EnableConfigurationProperties(value = SmsProperties.class)
public class SmsAutoConfiguration {

    @Autowired
    private SmsProperties smsProperties;

    /**
     * init aliyun sms handler
     *
     * @return
     */
    @Bean
    public SmsHandler aliyunSmsHandler() {
        AliyunSmsProperties aliyunSmsProperties = smsProperties.getAliyun();
        IAcsClient acsClient = null;
        if (aliyunSmsProperties.getInit()) {
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(),
                    aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessSecret());
            acsClient = new DefaultAcsClient(profile);
        }
        return new AliyunSmsHandler(acsClient, smsProperties);
    }

    /**
     * init yunzhixin sms handler
     *
     * @return
     */
    @Bean
    public SmsHandler yunZhiXinSmsHandler() {
        return new YunZhiXunSmsHandler(smsProperties);
    }

    @Bean
    public SmsHandler tencentSmsHandler() {
        return new TencentSmsHandler(smsProperties);
    }

    /**
     * init sms service
     *
     * @return
     */
    @Bean
    @Autowired
    public SmsService smsService(Map<String, SmsHandler> smsHandlerMap) {
        return new SmsService(smsHandlerMap, smsProperties);
    }

}
